<template>
  <!-- 用户列表 -->
  <div class="user-list">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row>
        <el-col :span="8">
          <div class="grid-content search-container">
            <el-input
              placeholder="请输入内容"
              v-model.trim="searchCont"
              clearable
              class="search-input"
              @clear="searchClear"
            >
            </el-input>
            <el-button
              type="info"
              plain
              icon="el-icon-search"
              @click="searchUser"
            ></el-button>
          </div>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserBtn">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表模板 -->
      <div class="user-table">
        <el-table :data="userData" border style="width: 100%">
          <el-table-column type="index" label="#" width="48"></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column prop="mobile" label="电话"> </el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column prop="mg_state" label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="modifyUserState(scope.row.id, scope.row.mg_state)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="editUser(scope.row.id)"
              ></el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="deleteUser(scope.row.id)"
              ></el-button>
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="assignRole(scope.row.id)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageTotal"
          :hide-on-single-page="false"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加用户弹出层 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisible"
      class="add-user-dialog"
    >
      <el-form
        :model="addUserForm"
        :rules="addUserFormRules"
        ref="addUserForm"
        class="demo-ruleForm"
        :label-position="labelPosition"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="addUserForm.tel"></el-input>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="info" @click="addUserReset('addUserForm')"
            >重置</el-button
          >
          <el-button type="primary" @click="addUserSubmit('addUserForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 编辑用户弹出层 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="dialogEditFormVisible"
      class="edit-user-dialog"
    >
      <el-form
        :model="editUserForm"
        :rules="addUserFormRules"
        ref="editUserForm"
        class="demo-ruleForm"
        :label-position="labelPosition"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="editUserForm.tel"></el-input>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button @click="dialogEditFormVisible = false">取消</el-button>
          <el-button type="primary" @click="editUserSubmit('editUserForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配角色弹出层 -->
    <el-dialog
      title="分配角色"
      :visible.sync="dialogRoleFormVisible"
      class="assign-role-dialog"
      @close="editUserForm.role=''"
    >
      <el-form
        :model="editUserForm"
        ref="assignRoleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="当前的用户：">
            <span v-text="editUserForm.username"></span>
        </el-form-item>
        <el-form-item label="当前的角色：">
            <span v-text="editUserForm.role"></span>
        </el-form-item>
        <el-form-item label="分配新角色：" prop="region">
          <el-select v-model="editUserForm.roleId" placeholder="请选择">
            <el-option :label="item.roleName" :value="item.id" v-for="item in roleList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button @click="dialogRoleFormVisible = false">取消</el-button>
          <el-button type="primary" @click="assignRoleSubmit()"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //用户名正则
    var userRule = /^[\u4E00-\u9FA5A-Za-z0-9_]{3,10}$/;
    var checkUsername = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error("请输入用户名"));
      } else {
        if (!userRule.test(value)) {
          callback(
            new Error(
              "用户名长度在3-10个字符之间，且只能包含数字、字母、汉字或下划线"
            )
          );
        } else {
          callback();
        }
      }
    };
    //密码正则
    var pwdRule = /(?=.*([a-zA-Z].*))(?=.*[0-9].*)[a-zA-Z0-9-*/+.~!@#$%^&*()]{6,15}$/;
    var checkPassword = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error("请输入密码"));
      } else {
        if (!pwdRule.test(value)) {
          callback(
            new Error(
              "密码长度在6-15个字符之间，至少包含数字跟字母，可以有字符"
            )
          );
        } else {
          callback();
        }
      }
    };
    //邮箱正则
    var emailRule = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    var checkEmail = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error("请输入邮箱"));
      } else {
        if (!emailRule.test(value)) {
          callback(new Error("请输入正确的邮箱格式，例如：123456@qq.com"));
        } else {
          callback();
        }
      }
    };
    //手机号正则
    var telRule = /^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\d{8}$/;
    var checkTel = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error("请输入手机号"));
      } else {
        if (!telRule.test(value)) {
          callback(new Error("请输入正确的手机号格式"));
        } else {
          callback();
        }
      }
    };

    return {
      searchCont: "", //搜索内容
      userData: [], //用户数据
      currentPage: 1, //分页器当前页码
      pageTotal: 0, //分页器总条数
      pageSize: 2, //每页显示条数
      pageSizes: [1, 2, 5, 10], //可选择的每页条数
      dialogFormVisible: false, //控制添加用户弹出层显示隐藏
      dialogEditFormVisible: false, //控制编辑用户弹出层显示隐藏
      dialogRoleFormVisible: false, //控制角色分配弹出层
      labelPosition: "left",
      loadingConfig: {
        //加载层参数配置
        target: ".add-user-dialog",
        fullscreen: true,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)",
        text: "拼命加载中",
      },
      addUserForm: {
        //添加用户表单的数据
        username: "",
        password: "",
        email: "",
        tel: ""
      },
      roleList: [],
      addUserFormRules: {
        username: [
          { validator: checkUsername, required: true, trigger: "blur" },
        ],
        password: [
          { validator: checkPassword, required: true, trigger: "blur" },
        ],
        email: [{ validator: checkEmail, required: true, trigger: "blur" }],
        tel: [{ validator: checkTel, required: true, trigger: "blur" }],
      },
      editUserForm: {
        //编辑用户表单的数据
        id: null,
        roleId: null,
        selectRoleId: null,
        username: "",
        email: "",
        tel: "",
        role:''
      },
    };
  },

  methods: {
    //获取用户数据
    getUserData() {
      //打开加载层
      var addUserLoading = this.$loading.service({
        target: ".add-user-dialog",
        fullscreen: true,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)",
        text: "拼命加载中",
      });
      this.$axios
        .get("/users", {
          params: {
            query: this.searchCont, //请求的搜索用户名关键词
            pagenum: this.currentPage, //请求的当前页码
            pagesize: this.pageSize, //请求的每页显示条数
          },
        })
        .then((res) => {
          if (res.meta.status == 200) {
            //关闭加载层
            this.$nextTick(() => {
              addUserLoading.close();
            });
            //设置分页器总条数
            this.pageTotal = res.data.total;
            //设置当前页
            this.currentPage = res.data.pagenum;
            //设置用户数据
            this.userData = res.data.users;
            //判断当前页是否为空
            if (this.pageTotal == (this.currentPage - 1) * this.pageSize) { 
                if (this.currentPage - 1 < 1) {
                    this.handleCurrentChange(1);
                } else {
                    this.handleCurrentChange(this.currentPage - 1);
                }
            }
          } else {
            //关闭加载层
            this.$nextTick(() => {
              addUserLoading.close();
            });
            this.$message.error(res.meta.msg);
          }
        });
    },
    handleSizeChange(val) {
      //切换每页条数重新获取用户数据
      this.pageSize = val;
      this.getUserData();
    },
    handleCurrentChange(val) {
      //切换页码时重新获取用户数据
      this.currentPage = val;
      this.getUserData();
    },
    addUserBtn() {
      //添加用户按钮触发弹出层
      this.dialogFormVisible = true;
    },
    addUserSubmit(formName) {
      //添加用户表单提交
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var addUserLoading = this.$loading.service({
            target: ".add-user-dialog",
            fullscreen: true,
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.1)",
            text: "拼命加载中",
          });
          this.$axios
            .post("/users", {
              username: this.addUserForm.username,
              password: this.addUserForm.password,
              email: this.addUserForm.email,
              mobile: this.addUserForm.tel,
            })
            .then((res) => {
              if (res.meta.status == 201) {
                //关闭加载层
                this.$nextTick(() => {
                  addUserLoading.close();
                });
                //打开消息弹窗
                this.$message({
                  message: res.meta.msg,
                  type: "success",
                });
                //重置添加用户表单
                this.$refs[formName].resetFields();
                //关闭弹出层
                this.dialogFormVisible = false;
                //重新渲染用户列表
                this.getUserData();
              } else {
                this.$nextTick(() => {
                  addUserLoading.close();
                });
                this.$message.error(res.meta.msg);
              }
            });
        } else {
          return false;
        }
      });
    },
    addUserReset(formName) {
      //重置添加用户表单
      this.$refs[formName].resetFields();
    },
    searchUser() {
      //搜索用户
      this.getUserData();
    },
    searchClear() {
      //清除搜索框后重新渲染默认用户列表
      this.searchCont = "";
      this.getUserData();
    },
    getUserInfo(id, cb) {
      //打开加载层
      var addUserLoading = this.$loading.service(this.loadingConfig);
      //根据ID查找用户信息
      this.$axios.get("/users/" + id).then((res) => {
        if (res.meta.status == 200) {
          this.editUserForm.id = res.data.id;
          this.editUserForm.username = res.data.username;
          this.editUserForm.email = res.data.email;
          this.editUserForm.tel = res.data.mobile;
          this.editUserForm.roleId = res.data.rid;
          //关闭加载层
          addUserLoading.close();
          //执行回调函数
          if (cb) {
            cb();
          }
        } else {
          //关闭加载层
          addUserLoading.close();
          //提示错误信息
          this.$message.error(res.meta.msg);
        }
      });
    },
    editUser(id) {
      this.getUserInfo(id, () => {
        //打开编辑用户的弹出层
        this.dialogEditFormVisible = true;
      });
    },
    editUserSubmit(formName) {
      //验证信息格式
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //打开加载层
          var addUserLoading = this.$loading.service(this.loadingConfig);
          //编辑用户提交
          this.$axios
            .put("/users/" + this.editUserForm.id, {
              email: this.editUserForm.email,
              mobile: this.editUserForm.tel,
            })
            .then((res) => {
              if (res.meta.status == 200) {
                //关闭加载层
                addUserLoading.close();
                //提示提交成功信息
                this.$message({
                  message: res.meta.msg,
                  type: "success",
                });
                //关闭编辑用户弹出层
                this.dialogEditFormVisible = false;
                //重新渲染用户列表
                this.getUserData();
              } else {
                //关闭加载层
                addUserLoading.close();
                //提示错误信息
                this.$message.error(res.meta.msg);
              }
            });
        } else {
          return false;
        }
      });
    },
    modifyUserState(id, bool) {
      //修改用户状态
      //打开加载层
      var addUserLoading = this.$loading.service(this.loadingConfig);
      this.$axios.put("/users/" + id + "/state/" + bool).then((res) => {
        if (res.meta.status == 200) {
          //关闭加载层
          addUserLoading.close();
          //提示成功信息
          this.$message({
            message: res.meta.msg,
            type: "success",
          });
          //重新渲染用户列表
          this.getUserData();
        } else {
          //关闭加载层
          addUserLoading.close();
          //提示失败信息
          this.$message.error(res.meta.msg);
          //重新渲染用户列表
          this.getUserData();
        }
      });
    },
    deleteUser(id) {
      //根据ID删除用户

      //调用确认弹框
      this.$confirm("此操作将永久删除该用户，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //打开加载层
          var addUserLoading = this.$loading.service(this.loadingConfig);
          this.$axios.delete("/users/" + id).then((res) => {
            if (res.meta.status == 200) {
              //关闭加载层
              addUserLoading.close();
              //提示删除成功消息
              this.$message({
                message: res.meta.msg,
                type: "success",
              });
              //重新渲染用户列表
              this.getUserData();
            } else {
              //关闭加载层
              addUserLoading.close();
              //提示失败信息
              this.$message.error(res.meta.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    assignRole(id) {
        //获取用户信息
        this.getUserInfo(id, this.getUserRole.bind(this));
        //获取角色列表
        this.getRoleList();
        //打开角色权限弹窗
        this.dialogRoleFormVisible = true;
        
    },
    assignRoleSubmit() {
        //打开加载层
          var addUserLoading = this.$loading.service(this.loadingConfig);
        //分配角色权限提交
        this.$axios.put('/users/' + this.editUserForm.id + '/role', {
           rid: this.editUserForm.roleId
        }).then((res) => {
            if (res.meta.status == 200) {
                //关闭加载层
                addUserLoading.close();
                //提示成功消息
                this.$message.success(res.meta.msg);
                //关闭弹出层
                this.dialogRoleFormVisible = false;
                //重新渲染用户列表
                this.getUserData();
            } else {
                //关闭加载层
                addUserLoading.close();
                //提示错误消息
                this.$message.error(res.meta.msg);
            }
        })
    },
    getRoleList() {
        //获取角色列表
        this.$axios.get('/roles').then((res) => {
            if (res.meta.status == 200) {
                this.roleList = res.data;
            } else {
                this.$message.error(res.meta.msg);
            }
        });
    },
    getUserRole() {
        //根据角色ID查询角色
        return this.$axios.get('/roles/' + this.editUserForm.roleId).then((res) => {
            if (res.meta.status == 200) {
                this.editUserForm.role = res.data.roleName;
                //执行回调函数
                // if (cb) {
                //     cb();
                // }
            } else {
                this.editUserForm.roleId = null;
                this.editUserForm.role = '';
                this.$message.error(res.meta.msg);
            }
        });
    }

  },
  mounted() {
    //模板挂在完成后获取用户数据
    this.getUserData();
    this.$emit('trans-route',this.$route.path);
  },
};
</script>

<style lang="less" scoped>


.el-col,
.user-table {
  padding: 0 10px;
}
</style>

<style lang="less">
.search-container {
  display: flex;
  align-items: center;
  .el-input {
    border-top-right-radius: 0 !important;
    border-bottom-right-radius: 0 !important;
  }
  .el-button {
    height: 40px;
    color: #909399 !important;
    border-color: #d3d4d6 !important;
    background-color: #f5f7fa !important;
    border-left: none;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    &:hover {
      color: #909399 !important;
      background-color: #f5f7fa !important;
      border-color: #d3d4d6 !important;
    }
  }
}
.search-container {
  .el-input__inner {
    border-top-right-radius: 0 !important;
    border-bottom-right-radius: 0 !important;
  }
}
.pagination {
  margin-top: 15px;
  padding: 0 10px;
}
.user-table {
  margin-top: 15px;
  thead th,
  tbody td {
    font-size: 12px !important;
  }
}
</style>